package me.helllp.dake.generator.engine.mybatis;

import freemarker.template.TemplateException;
import lombok.Getter;
import lombok.Setter;
import me.helllp.dake.generator.config.GeneratorEngineConfiguration;
import me.helllp.dake.generator.engine.RdbmsGenerator;
import me.helllp.dake.generator.meta.ProjectMetaData;
import me.helllp.dake.generator.meta.core.SmartMethod;
import me.helllp.dake.generator.utils.FileAndPathUtils;
import me.helllp.dake.generator.utils.XmlUtil;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.tree.DefaultElement;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

/**
 * 增加Mybatis查询方法的生成器
 */
@Getter
@Setter
public class MybatisMethodGenerator extends RdbmsGenerator {
    /**
     * 方法信息
     */
    private SmartMethod method;

    /**
     * 要写入的Mapper文件名称，没有扩展名
     */
    private String mapperFileName;

    /**
     * sql，未来可以基于sql自动解析method的内容
     */
    private String sqlContext;

    public MybatisMethodGenerator(ProjectMetaData projectMetaData) {
        super(projectMetaData);
    }

    @Override
    public void initGenerator(GeneratorEngineConfiguration engineConfiguration) throws TemplateException, IOException, InvocationTargetException, IllegalAccessException {
        super.initGenerator(engineConfiguration);
    }

    @Override
    public void generator() throws IOException, TemplateException {
        // 追加到xml文件中
        File xmlFile = FileAndPathUtils.pathAppend(getProjectMetaData().getSrcResourcePath(), "mapper", mapperFileName + "Mapper.xml");
        Document document = XmlUtil.loadXmlFile(xmlFile);
        document.getRootElement().add(makeElement());
        XmlUtil.writeXmlFile(document, xmlFile.getCanonicalPath());

        // TODO 追加到mapper接口文件中
//        String packageName = getProjectMetaData().getBasePackage() + ".mapper";
//        File packageFile = FileAndPathUtils.pathAppendPackage(getProjectMetaData().getSrcJavaPath(), packageName);
//        File javaFile = FileAndPathUtils.pathAppend(packageFile.getCanonicalPath(), mapperFileName + ".java");
//
//        ParseResult<CompilationUnit> cu = new JavaParser().parse(javaFile);
//        NodeList<Modifier> list = new NodeList<>();
//        list.add(Modifier.publicModifier());
//        CompilationUnit unit = cu.getResult().get();

    }

    private Element makeElement() {
        Element select = new DefaultElement("select");
        select.addAttribute("id", method.getName());
        select.addAttribute("resultType", method.getParameters().get(0).getType().makeFullName());
        select.setText(sqlContext);

        return select;
    }
}
